package com.gateway.filiter;



import cn.hutool.core.text.AntPathMatcher;
import cn.hutool.core.util.StrUtil;
import com.comon.core.constants.CacheConstants;
import com.comon.core.constants.Constants;
import com.comon.core.constants.HttpConstants;
import com.comon.core.domain.entity.LoginUser;
import com.comon.core.enums.UserIdentity;
import com.comon.core.utils.StringUtils;
import io.jsonwebtoken.Claims;
import com.alibaba.fastjson2.JSON;


import com.common.redis.service.RedisService;
import com.comon.core.domain.result.R;
import com.comon.core.enums.ResultCode;
import com.comon.core.utils.JwtUtils;
import com.gateway.properties.IgnoreWhiteProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

/**
 * 网关鉴权
 *
 */
@Component
@Slf4j                             //全局过滤器   重写getOrder()控制过滤器的先后顺序-数字越小越先执行
public class AuthFilter implements GlobalFilter, Ordered {

    // 排除过滤的 uri ⽩名单地址，在nacos⾃⾏添加
    @Autowired
    private IgnoreWhiteProperties ignoreWhite;


    @Autowired
    private RedisService redisService;

    @Override                 //一个 HTTP 请求和响应的交换过程
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();

        String url = request.getURI().getPath();   //请求的接口地址，跳过登录接口
        // 跳过不需要验证的路径,接口白名单中的接口都不需要进行身份验证
        if (matches(url, ignoreWhite.getWhites())) {
            return chain.filter(exchange);
        }
        System.out.println("AuthFilter已经启动！");
        //从http请求头中获取token
        String token = getToken(request);
        if (StrUtil.isEmpty(token)) {
            return unauthorizedResponse(exchange, "令牌不能为空");
        }
        Claims claims;
        try {
            claims = JwtUtils.parseToken(token);
            if (claims == null) {
                return unauthorizedResponse(exchange, "令牌已过期或验证不正确！");
            }
        } catch (Exception e) {
            return unauthorizedResponse(exchange, "令牌已过期或验证不正确！");
        }

        String userUUID = JwtUtils.getUserUUID(claims);
        boolean isLogin = redisService.hasKey(getTokenKey(userUUID));
        if (!isLogin) {
            return unauthorizedResponse(exchange, "登录状态已过期");
        }
        if (StringUtils.isEmpty(userUUID)) {
            return unauthorizedResponse(exchange, "令牌验证失败");
        }

        //token是正确的，并且没有过期
        // 判断redis存储  关于用户的身份认证信息是否对的
        LoginUser user = redisService.getCacheObject(getTokenKey(userUUID), LoginUser.class);
        if (url.contains(Constants.MASTER_URL_PREFIX) && !UserIdentity.ADMIN.getValue().equals(user.getIdentity())) {
            return unauthorizedResponse(exchange, "令牌验证失败");
        }
        if (url.contains(Constants.USER_URL_PREFIX) && !UserIdentity.ORDINARY.getValue().equals(user.getIdentity())) {
            return unauthorizedResponse(exchange, "令牌验证失败");
        }

        return chain.filter(exchange);
    }
    private Mono<Void> unauthorizedResponse(ServerWebExchange exchange, String msg) {
        log.error("[鉴权异常处理]请求路径:{}", exchange.getRequest().getPath());
        return webFluxResponseWriter(exchange.getResponse(), msg, ResultCode.FAILED_UNAUTHORIZED.getCode());

    }

    //组装
    public static Mono<Void> webFluxResponseWriter(ServerHttpResponse response, String msg, int code) {
        response.setStatusCode(HttpStatus.OK);
        response.getHeaders().add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
        R<?> result = R.fail(code, msg);
        DataBuffer dataBuffer = response.bufferFactory().wrap(JSON.toJSONString(result).getBytes());
        return response.writeWith(Mono.just(dataBuffer));
    }

    /**
     * @description: 查找指定url是否匹配指定匹配规则链表中的任意⼀个字符串
     * @param url
     * @param patternList     需要检查的匹配规则链表
     * @return: boolean 
    **/
    private boolean matches(String url, List<String> patternList) {
        if (StrUtil.isEmpty(url) || CollectionUtils.isEmpty(patternList)) {
            return false;
        }
            for (String pattern : patternList) {
                if (isMatch(pattern, url)) {
                    return true;
                }
            }
        return false;
    }
    /**
     * 判断url是否与规则匹配
     * 匹配规则中：
     * ? 表⽰单个字符;
     * * 表⽰⼀层路径内的任意字符串，不可跨层级;
     * ** 表⽰任意层路径;
     *
     * @param pattern 匹配规则
     * @param url 需要匹配的url
     * @return 是否匹配
     */
    private boolean isMatch(String pattern, String url) {
        AntPathMatcher matcher = new AntPathMatcher();
        return matcher.match(pattern, url);
    }

    /**
     * 获取缓存key
     */
    private String getTokenKey(String token) {
        return CacheConstants.LOGIN_TOKEN_KEY + token;
    }

    /**
     * 获取请求token
     */
    private String getToken(ServerHttpRequest request) {
        String token = request.getHeaders().getFirst(HttpConstants.AUTHENTICATION);
        // 如果前端设置了令牌前缀，则裁剪掉前缀
        if (StringUtils.isNotEmpty(token) && token.startsWith(HttpConstants.PREFIX)) {
            token = token.replaceFirst(HttpConstants.PREFIX, StringUtils.EMPTY);
        }
        return token;
    }

    /**
     * @description: 控制过滤器的执行顺序
     * @param
     * @return: int
     **/
    @Override
    public int getOrder() {
        return -200;
    }


}